<template>
  <div class="admin__page">
    <h1>欢迎管理员</h1>
    <button @click="goToLogin">返回登录页面</button>
    <table>
      <thead>
      <tr>
        <th>姓名</th>
        <th>年龄</th>
        <th>地址</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="(user,index) in users" :key="index">
        <td>{{ user.name }}</td>
        <td>{{ user.age }}</td>
        <td>{{ user.address }}</td>
        <td>
          <button @click="editUser(index)">编辑</button>
          <button @click="deleteUser(index)">删除</button>
        </td>
      </tr>
      </tbody>
    </table>
    <button @click="openAddUserModal">新增用户</button>
    <div v-if="isAddUserModalOpen" class="modal">
      <div class="modal - content">
        <span class="close" @click="closeEditUserModal">&times;</span>
        <h2>编辑用户</h2>
        <input type="text" v-model="editUser.name" placeholder="姓名"/>
        <input type="number" v-model="editUser.age" placeholder="姓名"/>
        <input type="text" v-model="editUser.address" placeholder="年龄"/>
        <button @click="saveEditedUser">保存</button>
      </div>
    </div>

  </div>
</template>
<script>
export default{
  data(){
    return{
      user:[
        {name:'张三',age:25,address:'北京'},
        {name:'李四',age:30,address:'上海'},
      ],
      isAddUserModalOpen:false,
      newUser:{name:'',age:null,address:''},
      isEditUserModalOpen:false,
      editUser:{}
    };
  },
  methods:{
    goToLogin(){
      this.$router.push('/login');
    },
    openAddUserModal(){
      this.isAddUserModalOpen = true;
    },
    closeAddUserModal(){
      this.isAddUserModalOpen = false;
      this.newUser = {name:'',age:'',address:''};
    },
    addUser(){
      this.user.push(this.newUser);
      this.closeAddUserModal();
    },
    editUser(index){
      this.editUser = {...this.user[index]};
      this.isEditUserModalOpen = true;
    },
    closeEditUserModal(){
      this.isEditUserModalOpen = false;
      this.editUser={};
    },
    saveEditedUser(){
      let index = this.users.findIndex(user=>user.name===this.editUser.name);
      this.users[index].age=this.editUser;
      this.closeEditUserModal();
    },
    deleteUser(index){
      if (confirm('是否真的要删除这条记录？')){
        this.users.splice(index,1);
      }
    }
  }
}

</script>
<style scoped>
.modal{
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0, 0, 0, 0.4);
}
.modal-content{
  background-color: #fefefe;
  margin: 15% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}
.close{
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}
.close:hover,
.close:focus{
  color: black;
  text-decoration: none;
  cursor: pointer;
}
</style>
